import ci_api


def sort_group(dsl_groups, groups, ci_url):
    dsl_groups = generate_id_name(dsl_groups)
    groups = delete_group(dsl_groups, groups)
    for i in range(len(dsl_groups)):
        msg = ci_api.update_group_sort(ci_url, dsl_groups[i]['id'], groups[i]['id'])
        if msg:
            print('error:', '项目组排序失败', msg, flush = True)
            break
        groups.remove(dsl_groups[i])
        groups.insert(i, dsl_groups[i])


def sort_project(dsl_projects, projects, ci_url, group_id):
    projects = set_id(dsl_projects, projects)
    for i in range(len(dsl_projects)):
        if dsl_projects[i]['name'] != projects[i]['name']:
            msg = ci_api.update_project_sort(ci_url, group_id, dsl_projects[i]['id'], projects[i]['id'])
            if msg:
                print('error:', '排序失败', msg, flush = True)
                break
            projects.remove(dsl_projects[i])
            projects.insert(i, dsl_projects[i])


def generate_id_name(items):
    return [{'id': item['id'], 'name': item['name']} for item in items]


# 设置ID，删除不在dsl中的项目
def set_id(items, item_ids):
    delete_list = []
    item_ids = generate_id_name(item_ids)
    for item_id in item_ids:
        flag = True
        for item in items:
            if item['name'] == item_id['name']:
                item['id'] = item_id['id']
                flag = False
                break
        if flag:
            delete_list.append(item_id)
    for item_id in delete_list:
        item_ids.remove(item_id)
    return item_ids


def delete_group(dsl_groups, groups):
    delete_list = []
    groups = generate_id_name(groups)
    for group in groups:
        flag = True
        for dsl_group in dsl_groups:
            if dsl_group['name'] == group['name']:
                dsl_group['id'] = group['id']
                flag = False
                break
        if flag:
            delete_list.append(group)
    for item_id in delete_list:
        groups.remove(item_id)
    return groups
